package NG::Chat::Client::Message;
use strict;
use warnings;
use utf8;

require Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(
HttpRequest
HttpParse
SockRequest
SockParse
);
use JSON::XS;
use HTTP::Parser::XS qw(parse_http_response HEADERS_AS_HASHREF);
#use NG::Chat::Util;
use NG::Sys::Datetime;

sub HttpRequest {
	my ($self,$message) = @_;
	$message->{ts} = unixtime2hms();
	$message->{rid} = $self->{rid}++;
	$message->{sid} = $self->{sid} if $self->{sid};
	$message->{chanel} ||= $self->{chanel} || "default";
	
	my $command = $message->{cmd};

	my $body = encode_json($message);

	my $to_send = "POST /".$self->{path}.$command." HTTP/1.1\n"
		."Content-Length: ".length($body)."\n"
		."Content-Type: text/x-javascript\n"
		."Host: ".$self->{host}."\n"
		."Connection: close\n"
		."\n"
		.$body;
	return $to_send;
}
sub HttpParse {
	my $ref_str = shift;
	my($ret, $mv, $status, $mss, $headers) = parse_http_response($$ref_str, HEADERS_AS_HASHREF);
	if($ret > 0) {
		if($status == 200){
			my $body = substr($$ref_str,$ret);
			if($headers->{'content-length'} && $headers->{'content-length'} > length($body)){
				return 0;
			}else{
				$$ref_str = "";
				my $msg;
				eval {
					$msg = decode_json($body);
				};
				if($@){
					return {
						error => 10,
						text =>"Broke json: '$!'",
						};
				}
				return $msg;
			}
		}else{
			my $body = substr($$ref_str,$ret);
			$$ref_str = "";
			return {
				error => 10,
				text =>"BAD RESPONSE: ".$status,
				#body => $body,
				headers => $headers,
				mss => $mss,
				now => unixtime2hms(),
				};
		}
	}elsif($ret == -2){
		$$ref_str = "";
		return {
			error => 10,
			text =>"Broken response",
			};
	}else{
		return 0;
	}
}
sub SockRequest {
	my ($self,$message) = @_;
	$message->{ts} = unixtime2hms();
	$message->{rid} = $self->{rid}++;
	$message->{sid} = $self->{sid} if $self->{sid};
	$message->{chanel} ||= $self->{chanel} || "default";
	
	my $to_send = encode_json($message).chr(0);

	return $to_send;
}
sub SockParse {
	my $ref_str = shift;
	if((my $i = index($$ref_str,chr(0))) == -1){
		return 0;
	}else{
		my $body = substr($$ref_str,0,$i+1,"");
		my $msg;
		eval {
			$msg = decode_json($body);
		};
		if($@){
			return {
				error => 10,
				text =>"Broke json: '$!'",
				};
		}
		return $msg;
	}
}

1;
